package io.kiki.sba.registry.remoting.netty;


import io.kiki.sba.registry.api.ChannelHandler;
import io.kiki.stack.netty.processor.AsyncContext;
import io.kiki.stack.netty.processor.BizContext;
import io.kiki.stack.netty.userProcessor.AsyncUserProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Executor;


public class AsyncUserProcessorAdapter extends AsyncUserProcessor {

    private static final Logger logger = LoggerFactory.getLogger(AsyncUserProcessorAdapter.class);

    private final ChannelHandler channelHandler;


    public AsyncUserProcessorAdapter(ChannelHandler channelHandler) {
        this.channelHandler = channelHandler;
    }


    @Override
    public void asyncHandleRequest(BizContext bizContext, AsyncContext asyncContext, Object object) {
        try {
            Channel channel = new Channel(bizContext.getChannel());
            channel.setAsyncContext(asyncContext);
            channelHandler.messageReceived(channel, object);
        } catch (Throwable e) {
            logger.error("Handle request error!", e);
            throw new RuntimeException("Handle request error!", e);
        }
    }

    @Override
    public String interest() {
        if (channelHandler.interest() != null) {
            return channelHandler.interest().getName();
        }

        return null;
    }

    @Override
    public Executor getExecutor() {
        return channelHandler.getExecutor();
    }
}
